import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import instance from '../axios/index';
import { Button, Cell, Checkbox, Popup, } from '@nutui/nutui-react'
import '../css/cartOrders.css'
import { useSelector, useDispatch } from 'react-redux';

import Address from '../components/Address';
export default function CartOrders() {
    let oForm = useRef();
    const navigate = useNavigate();
    const [showBottom, setShowBottom] = useState(false)
    // const [useName, setUseName] = useState(useSelector(state => state.cart.useList))
    // console.log(`useName`, useName);
    
    // 从 URL 查询参数获取传递来的 ids
    const [searchParams] = useSearchParams(); // 添加 useSearchParams
    const ids = searchParams.get('ids'); // 从查询参数获取 ids
    console.log(`传递来的 ids`, ids);
    // 获取日期
    const time = new Date();
    const month = time.getMonth() + 1; // 获取月份（注意：月份是从0开始的，所以要加1）
    const day = time.getDate() + 1; // 获取日期
    // 其他代码...
    const [orderlist, setOrderlist] = useState([]);
    // 获取价格
    const totalAmount = orderlist.reduce((pre, cur) => {
        return cur.isChecked ? pre + cur.price * cur.num : pre;
    }, 0);
    // 获取商品名称
    const totalName = orderlist.reduce((pre, cur) => {
        return cur.isChecked? pre + cur.name + '、' : pre;
    }, '');
    console.log(`总价`, totalName);

    // 选中商品的 ID
    const selectedIds = orderlist.filter(item => item.isChecked).map(item => item._id);
    // 选中商品的总金额，添加初始值
    const selectedTotalAmount = orderlist.reduce((pre, cur) => {
        // （previous）是累加器，表示上一次计算的结果；（current）是当前正在处理的数组元素；
        return cur.isChecked ? pre + cur.price * cur.num : pre;
    }, 0);
    const [address, setAddress] = useState(localStorage.getItem('endAddress') || '河北省保定市莲池区北苑小区1号楼1单元101室')
    const [user, setUser] = useState({
        name:'',
        phone:''
    })
    // 点击复选框进行选中
    const handleClickcheck = (_id) => {
        console.log(_id)
        instance({
            url: `/cart/change?_id=${_id}`,
            method: 'post'
        }).then(res => {
            if (res.data.code === 200) {
                getlist()
            } else {
                alert(res.data.msg)
            }
        })
    }
    // 点击减号进行--
    const handleClickReduce = (_id) => {
        console.log(_id)
        instance({
            url: `/cart/reduce?_id=${_id}`,
        }).then(res => {
            if (res.data.code === 200) {
                getlist()
            } else {
                alert('最少选中一件商品')
            }
        })
    }
    // 点击加号进行++
    const handleClickAdd = (_id) => {
        console.log(_id)
        instance({
            url: `/cart/add?_id=${_id}`,
        }).then(res => {
            if (res.data.code === 200) {
                getlist()
            } else {
                alert('库存不足了，请等待补货')
            }
        })
    }
    const getlist = () => {
        if (ids) {
            instance({
                url: `/cart/submit?ids=${ids}`
            }).then(res => {
                const orders = res.data.Orderlist;
                setOrderlist(orders)
            }).catch(error => {
                console.error('获取订单数据失败:', error);
            });
        } else {
            console.log('未传递任何商品 ID');
        }
    }
    const yibuFetcher = async () => {
        const id = sessionStorage.getItem('id')
        instance({
            url: `/my/getUseName?id=${id}`,
        }).then(res => {
            console.log(res.data.data.name);
            
            const arr ={...user}
            arr.name = res.data.data.name
            arr.phone = res.data.data.phoneNumber
           setUser(arr)
        })
    }
    useEffect(() => {
        if (ids) {
            getlist()
        }
        yibuFetcher()
    }, [ids])
    return (
        <div className='orderbigbox'>
            <div className='ordertopbox'>
                <div className='dingdanqueren'>
                    <p onClick={() => navigate(-1)}>返回</p>
                    <p style={{ fontSize: '20px', fontWeight: 'bold', color: 'white', paddingTop: '10px' }}>确认订单</p>
                    <p style={{ fontSize: '16px', color: 'white', marginTop: '10px' }}>{address}</p>
                </div>
                <div className='dizhi'>
                    <p style={{ fontSize: '18px', fontWeight: 'bolder' }}>收货人：{user.name}</p>
                    <p style={{ fontSize: '18px' }}>{user.phone}</p>
                </div>
                <div className='xuanzedizhi'>
                    <Address></Address>
                </div>
            </div>
            <div className="orderMiddlebox">
                {
                    orderlist.map(item => (
                        <div className="orderItembox" key={item._id}>
                            <Cell className="nut-cell" style={{ width: '22px', textAlign: 'center', paddingLeft: '0px' }}>
                                <Checkbox
                                    style={{ '--nut-icon-width': '20px', '--nut-icon-height': '100%' }}
                                    checked={item.isChecked}
                                    onChange={() => handleClickcheck(item._id)}
                                />
                            </Cell>
                            <img src={item.img} alt="" />
                            <div className="orderItemrightbox">
                                <p>{item.name}</p>
                                <div className="orderItemrightbox2">
                                    <span>￥{item.price}</span>
                                    <p>
                                        <button onClick={() => handleClickReduce(item._id)}>-</button>
                                        <input type="text" value={item.num} />
                                        <button onClick={() => handleClickAdd(item._id)}>+</button>
                                    </p>
                                </div>
                            </div>
                        </div>
                    ))
                }
                <div className='tishixinxi'>
                    <svg t="1733055423454" className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4772" width="25" height="25"><path d="M512 42.688l350.592 77.888a42.688 42.688 0 0 1 33.408 41.664v426.112a256 256 0 0 1-113.984 212.992L512 981.376 241.984 801.28A256 256 0 0 1 128 588.416V162.24a42.688 42.688 0 0 1 33.408-41.6L512 42.624z m189.952 308.16l-211.2 211.136-120.64-120.64-60.352 60.288 181.056 181.056 271.488-271.552-60.352-60.288z" fill="#67C23A" p-id="4773"></path></svg>
                    <p>如您购买的商品有任何问题，请直接与购买门店<br />
                        联系，门店会为您处理，让您售后无忧</p>
                </div>
            </div>
            <Popup
                overlayClassName="Popup"
                visible={showBottom}
                position="bottom"
                onClose={() => {
                    setShowBottom(false)
                }}
            >
                <div className='tanchuceng'>
                    <div className='tanchucengtop'>
                        <p>{month}月{day}日提货</p>
                    </div>
                    <p style={{ color: 'rgb(200, 12, 12)', paddingTop: '10px', fontSize: '16px' }}>
                        此商品需要您到店自提，请仔细确认地址!
                    </p>
                    <div className='tanchucengContent'>
                        <p style={{ fontSize: '16px', fontWeight: 'bold', paddingTop: "20px" }}>自提店：{address}</p>
                    </div>
                    {/* 用于展示form表单 */}
                    <div ref={oForm}></div>
                    <div className='tanchucengButton'>
                        <Button type="warning" onClick={() => {
                            setShowBottom(false)
                        }}>
                            取消订单
                        </Button>
                        <Button type="danger" onClick={() => {
                            instance({
                                url: `/cart/alipay`,
                                method: 'post',
                                data: { ids: selectedIds.join(','), totalAmount: selectedTotalAmount ,totalName:totalName}
                            }).then(res => {
                                console.log(res.data)
                                // 将form表单插入到页面中
                                oForm.current.innerHTML = res.data;
                                // 自动调用form表单  document.forms 获取当前页面中所有的表单集合 [form,form]
                                document.forms[0].submit();
                            })
                        }}>
                            确认订单
                        </Button>

                    </div>
                </div>
            </Popup>
            <div className="orderBottombox">
                <p>
                    <span style={{ fontWeight: 'bold' }}>合计:</span>
                    <span style={{ fontWeight: 'bold', color: 'red', fontSize: '20px' }}>￥{totalAmount}</span>
                </p>
                <Button type="primary" onClick={() => {
                    setShowBottom(true)

                }}>
                    提交订单
                </Button>
            </div>
        </div>
    )
}